package qlsl.androiddesign.api.http.service.commonservice;

import android.graphics.Bitmap;
import android.support.annotation.LayoutRes;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import qlsl.androiddesign.api.activity.R;
import qlsl.androiddesign.api.activity.baseactivity.FunctionActivity;
import qlsl.androiddesign.api.application.SoftwareApplication;
import qlsl.androiddesign.api.constant.MessageConstant;
import qlsl.androiddesign.api.method.HttpMethod;
import qlsl.androiddesign.api.util.commonutil.BitmapCompressor;
import qlsl.androiddesign.api.util.commonutil.CacheManager;
import qlsl.androiddesign.api.util.commonutil.ValueUtil;
import qlsl.androiddesign.api.util.commonutil.ViewUtils;

/**
 * 类描述：系统公用工具类模块
 * 需要传入的键：****
 * 传入的值类型：****
 * 传入的值含义：****
 * 是否必传：****
 * 作者：郑朝军 on 2017/6/14 11:29
 * 邮箱：1250393285@qq.com
 * 公司：武汉智博创享科技有限公司
 * 修改人：郑朝军 on 2017/6/14 11:29
 * 修改备注：
 */
public class CommonUtilsService<T extends FunctionActivity> extends MemberService<T>
{
    private String className = getClassName(CommonUtilsService.class);

    /**
     * 高质量压缩图片,可能会造成泄露,请谨慎使用<br/>
     *
     * @param paths     压缩图片路径 <br/>
     * @param secondDir 图片存放路径 可空  默认存放路径 /storage/emulated/0/Android/data/com.zerogis
     *                  .xdfeedwater/cache/picture<br/>
     * @param suffix    生成图片名称 可空 <br/>
     */
    public void compressFiles(final String[] paths, final String secondDir, final String suffix)
    {
        final String method = "compressFiles";
        getV().showProgressBar();
        Flowable.create(new FlowableOnSubscribe<Object>()
        {
            @Override
            public void subscribe(FlowableEmitter<Object> e) throws Exception
            {
                try
                {
                    List<File> pictureFiles = new ArrayList<File>();
                    for (int index = 0, size = paths.length; index < size; index++)
                    {
                        File file = new File(paths[index]);
                        pictureFiles.add(file);
                    }

                    List<File> compressFiles = new ArrayList<File>();
                    String[] compressFilesPath = new String[paths.length];

                    for (int index = 0, size = pictureFiles.size(); index < size; index++)
                    {
                        File file = pictureFiles.get(index);
                        Bitmap sampleBitmap = BitmapCompressor.decodeSampledBitmapFromFile(file
                                .getAbsolutePath());
                        Bitmap compressBitmap = BitmapCompressor.compressBitmap(sampleBitmap);
                        File compressFile = BitmapCompressor.copyDataToFile(getV(),
                                compressBitmap,
                                secondDir, suffix + index);
                        compressFiles.add(compressFile);
                        compressFilesPath[index] = compressFile.getAbsolutePath();
                    }

                    HashMap<String, Object> map = new HashMap<String, Object>();
                    map.put("File", compressFiles);
                    map.put("FilePath", compressFilesPath);

                    e.onNext(map);
                    e.onComplete();
                }
                catch (Exception exception)
                {
                    exception.printStackTrace();
                    outputException(e, exception,className);
                }
            }
        }, BackpressureStrategy.BUFFER)
                .compose(getScheduler())
                .compose(getV().bindToLifecycle())
                .subscribe(createSubscriber(method));
    }

    /**
     * 高质量压缩图片,可能会造成泄露,请谨慎使用<br/>
     *
     * @param paths     压缩图片路径 <br/>
     * @param secondDir 图片存放路径 可空  默认存放路径 /storage/emulated/0/Android/data/com.zerogis
     *                  .xdfeedwater/cache/picture<br/>
     * @param suffix    生成图片名称 可空 <br/>
     */
    public void compressFiles(final String paths, final String secondDir, final String suffix)
    {
        final String method = "compressFiles";
        getV().showProgressBar();
        Flowable.create(new FlowableOnSubscribe<Object>()
        {
            @Override
            public void subscribe(FlowableEmitter<Object> e) throws Exception
            {
                try
                {
                    List<File> pictureFiles = new ArrayList<File>();
                    File filep = new File(paths);
                    pictureFiles.add(filep);

                    List<File> compressFiles = new ArrayList<File>();
                    String compressFilesPath = new String();

                    File file = pictureFiles.get(0);
                    Bitmap sampleBitmap = BitmapCompressor.decodeSampledBitmapFromFile(file
                            .getAbsolutePath());
                    Bitmap compressBitmap = BitmapCompressor.compressBitmap(sampleBitmap);
                    File compressFile = BitmapCompressor.copyDataToFile(getV(),
                            compressBitmap,
                            secondDir, suffix + 0);
                    compressFiles.add(compressFile);
                    compressFilesPath = compressFile.getAbsolutePath();

                    HashMap<String, Object> map = new HashMap<String, Object>();
                    map.put("File", compressFiles);
                    map.put("FilePath", compressFilesPath);

                    e.onNext(map);
                    e.onComplete();
                }
                catch (Exception exception)
                {
                    exception.printStackTrace();
                    outputException(e, exception,className);
                }
            }
        }, BackpressureStrategy.BUFFER)
                .compose(getScheduler())
                .compose(getV().bindToLifecycle())
                .subscribe(createSubscriber(method));
    }

    /**
     * 高质量压缩图片,可能会造成泄露,请谨慎使用<br/>
     *
     * @param pictureFiles 压缩图片路径 <br/>
     * @param secondDir    图片存放路径 可空  默认存放路径 /storage/emulated/0/Android/data/com.zerogis
     *                     .xdfeedwater/cache/picture<br/>
     * @param suffix       生成图片名称 可空 <br/>
     */
    public void compressFiles(final List<File> pictureFiles, final String secondDir, final String
            suffix)
    {
        final String method = "compressFiles";
        getV().showProgressBar();
        Flowable.create(new FlowableOnSubscribe<Object>()
        {
            @Override
            public void subscribe(FlowableEmitter<Object> e) throws Exception
            {
                try
                {
                    List<File> compressFiles = new ArrayList<File>();
                    List<String> compressFilesPath = new ArrayList<String>();
                    for (int index = 0, size = pictureFiles.size(); index < size; index++)
                    {
                        File file = pictureFiles.get(index);
                        Bitmap sampleBitmap = BitmapCompressor.decodeSampledBitmapFromFile(file
                                .getAbsolutePath());
                        Bitmap compressBitmap = BitmapCompressor.compressBitmap(sampleBitmap);
                        File compressFile = BitmapCompressor.copyDataToFile(getV(), compressBitmap,
                                secondDir, suffix + index);
                        compressFiles.add(compressFile);
                        compressFilesPath.add(compressFile.getAbsolutePath());
                        Log.e("zcj", "compressFilesPath===" + compressFilesPath.get(index));
                    }
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    map.put("File", compressFiles);
                    map.put("FilePath", compressFilesPath);

                    e.onNext(map);
                    e.onComplete();
                }
                catch (Exception exception)
                {
                    exception.printStackTrace();
                    outputException(e, exception,className);
                }
            }
        }, BackpressureStrategy.BUFFER)
                .compose(getScheduler())
                .compose(getV().bindToLifecycle())
                .subscribe(createSubscriber(method));
    }


    /**
     * 关联图层
     */
    public void queryRelationLayer()
    {
        final String method = "queryRelationLayer";
        getV().showProgressBar();
        Flowable.create(new FlowableOnSubscribe<Object>()
        {
            @Override
            public void subscribe(FlowableEmitter<Object> e) throws Exception
            {
                try
                {

                }
                catch (Exception exception)
                {
                    exception.printStackTrace();
                    outputException(e, exception,className);
                }
            }
        }, BackpressureStrategy.BUFFER)
                .compose(getScheduler())
                .compose(getV().bindToLifecycle())
                .subscribe(createSubscriberOther(method));
    }

    /**
     * 查询缓存
     */
    public void queryCache(final String key, final boolean refresh, final int mCurrentPage)
    {
        final String method = "queryCache";
        getV().showProgressBar();
        Flowable.create(new FlowableOnSubscribe<Object>()
        {
            @Override
            public void subscribe(FlowableEmitter<Object> e) throws Exception
            {
                try
                {
                    Serializable base = null;
                    if (!HttpMethod.isNetworkConnect())
                    {
                        base = CacheManager.readObject(SoftwareApplication.getInstance(), key);
                    }
                    // 第一页若不是主动刷新，缓存存在，优先取缓存的
                    if (CacheManager.isExistDataCache(SoftwareApplication.getInstance(), key) && !refresh
                            && mCurrentPage == 0)
                    {
                        base = CacheManager.readObject(SoftwareApplication.getInstance(), key);
                    }
                    // 其他页数的，缓存存在以及还没有失效，优先取缓存的
                    if (CacheManager.isExistDataCache(SoftwareApplication.getInstance(), key)
                            && !CacheManager.isCacheDataFailure(SoftwareApplication.getInstance(), key)
                            && mCurrentPage != 0)
                    {
                        base = CacheManager.readObject(SoftwareApplication.getInstance(), key);
                    }
                    e.onNext(base);
                    e.onComplete();
                    outputMessageInfo("WHAT_OTHER_DATA_SUCCESS", MessageConstant.MSG_UNKOW_FAILED,
                            MessageConstant.MSG_UNKOW_FAILED, className,
                            method);
                }
                catch (Exception exception)
                {
                    exception.printStackTrace();
                    outputException(e, exception,className);
                }
            }
        }, BackpressureStrategy.BUFFER)
                .compose(getScheduler())
                .compose(getV().bindToLifecycle())
                .subscribe(createSubscriberOther(method));
    }

    /**
     * 保存缓存
     */
    public void createCacheObj(final Serializable seri, final String key)
    {
        final String method = "createCacheObj";
        getV().showProgressBar();
        Flowable.create(new FlowableOnSubscribe<Object>()
        {
            @Override
            public void subscribe(FlowableEmitter<Object> e) throws Exception
            {
                try
                {
                    boolean cacheSucess = CacheManager.saveObject(
                            SoftwareApplication.getInstance(), seri, key);

                    e.onNext(cacheSucess);
                    e.onComplete();
                    outputMessageInfo("WHAT_OTHER_DATA_SUCCESS", MessageConstant.MSG_UNKOW_FAILED,
                            MessageConstant.MSG_UNKOW_FAILED, className,
                            method);
                }
                catch (Exception exception)
                {
                    exception.printStackTrace();
                    outputException(e, exception,className);
                }
            }
        }, BackpressureStrategy.BUFFER)
                .compose(getScheduler())
                .compose(getV().bindToLifecycle())
                .subscribe(createSubscriberOther(method));
    }
    /**
     * 判断当前Activity是否被销毁
     *
     * @return
     */
    public boolean isActivityNull()
    {
        FunctionActivity activity = m_weakActivity.get();
        if (activity == null)
        {
            return true;
        }
        return false;
    }

    /**
     * 设置左边数据,添加到内容布局,需要传递资源
     *
     * @param map
     * @param content
     * @param resource
     * @return
     */
    public ViewGroup setLayoutLeft(final HashMap<String, Object> map, ViewGroup content, @LayoutRes int resource)
    {
        FunctionActivity activity = m_weakActivity.get();
        if (activity == null)
        {
            return null;
        }
        ViewGroup viewEdit = (ViewGroup) activity.getLayoutInflater().inflate(resource, null);
        setLayoutLeft(map, content, viewEdit);
        return viewEdit;
    }


    public ViewGroup setLayoutLeft(final HashMap<String, Object> map, ViewGroup content)
    {
        FunctionActivity activity = m_weakActivity.get();
        if (activity == null)
        {
            return null;
        }
        ViewGroup viewEdit = (ViewGroup) activity.getLayoutInflater().inflate(R.layout.listitem_common_edit, null);
        setLayoutLeft(map, content, viewEdit);
        return viewEdit;
    }

    /**
     * 设置左边数据,添加到内容布局
     *
     * @param map
     * @param content
     * @param
     */
    private ViewGroup setLayoutLeft(final HashMap<String, Object> map, ViewGroup content, ViewGroup viewEdit)
    {
        TextView tv_text = (TextView) viewEdit.findViewById(R.id.tv_text);
        TextView tv_xing = (TextView) viewEdit.findViewById(R.id.tv_xing);
        String text = (String) map.get("text");
        Integer isNull = (Integer) map.get("isNull");
        boolean bNull = ValueUtil.isEmpty(isNull) || isNull != 0 ? true : false;
        tv_text.setText(text + ":");
        if (bNull)
        {
            tv_xing.setVisibility(View.INVISIBLE);
        }
        else
        {
            tv_xing.setVisibility(View.VISIBLE);
        }
        ViewUtils.addView(content, viewEdit);
        return viewEdit;
    }

    /**
     * 添加edit布局(可在主或子线程中执行,减少阻塞)
     *
     * @param map
     * @param content
     */
    public void LoadEditTextLayout(final HashMap<String, Object> map, ViewGroup content)
    {
        ViewGroup viewEdit = setLayoutLeft(map, content);
        EditText et_edit = (EditText) viewEdit.findViewById(R.id.et_content);
        String value = (String) map.get("value");
        Integer isEdit = (Integer) map.get("isEdit");
        boolean bEdit = ValueUtil.isEmpty(isEdit) || isEdit != 0 ? false : true;

        et_edit.setVisibility(View.VISIBLE);
        et_edit.setText(value);
        et_edit.setTag(map);
        if (bEdit)
        {
            et_edit.setEnabled(false);
        }
        else
        {
            et_edit.setEnabled(true);
        }
    }

    public void LoadSpinnerLayout(final HashMap<String, Object> map, ViewGroup content)
    {
        ViewGroup viewEdit = setLayoutLeft(map, content);
        ViewGroup llSpaceView = (ViewGroup) viewEdit.findViewById(R.id.ll_spaceView);
        Spinner spaceView = (Spinner) viewEdit.findViewById(R.id.spaceView);

        llSpaceView.setVisibility(View.VISIBLE);

        String[] array = null;
        array = viewEdit.getContext().getResources().getStringArray(R.array.setting);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(viewEdit.getContext(), R.layout
                .common_listitem_spinner, R.id.tv_text, array);
        spaceView.setAdapter(adapter);
        adapter.setDropDownViewResource(R.layout.common_listitem_spinner_dropdown);
    }
}
